<template>
  <div>
    <!-- <Text />
  <Tupu/> -->
    <FileUpload :multiple="true" @onChange="onChange" accept=".mp4"
      >上传</FileUpload
    >
    <div v-for="(item, index) in fileList" :key="index">
      {{ item.name }}
      {{ item.progressStatus }}
      {{ item.percentage }}
      <el-progress
        :percentage="item.percentage"
        :stroke-width="12"
        :text-inside="true"
        status=""
      >
        <span>ssdfsd</span>
      </el-progress>
       <button @click="cancelUpload(item)" v-if="item.progressStatus === 'active'">取消上传</button>
    </div>
  </div>
</template>
<script setup>
import { onBeforeMount, onMounted, reactive, ref } from "vue";
import { getFileMd5 } from "./utils/index.js";
import axios from "axios";
import FileUpload from "./components/FileUpload.vue";
const emits = defineEmits([]);
const props = defineProps({});
const fileList = ref([]);
//判断文件是否存在接口
const uploadcheckFile = () => {
  return new Promise((resolve, reject) => {
    resolve({ code: 200 });
  });
};
//获取url的接口
const getPresignedUrl = () => {
  return new Promise((resolve, reject) => {
    resolve("https://www.baidu.com");
  });
};
//创建切片
function createThunk(file, size = 1024 * 1024 * 5) {
  const res = []; //文件切片后的数组
  let cur = 0;
  while (cur < file.size) {
    res.push({ tmpFile: file.slice(cur, cur + size) });
    cur += size;
  }
  return res;
}
const startUpload = async (file) => {
  const chunks = createThunk(file.raw);
  file.chunks = chunks.length;
  // 更新已上传切片数量
  // const interval = setInterval(() => {
  //   file.chunk++;
  //   // 更新百分比
  //   file.percentage = Math.round((file.chunk / file.chunks) * 100);
  //   console.log(file.percentage, "percentage");
  //   if (file.percentage === 100) clearInterval(interval);
  // }, 1000);

  try {
     // 创建 abort controller
    const abortController = new AbortController();
    file.abortController = abortController;
    for (const item of chunks) {
      const presignedUrl = await getPresignedUrl({
        fileName: file.name,
        bucket: "kb-temple-test",
      });

      // 上传当前切片
      const uploadFileRes = await axios({
        url: presignedUrl,
        method: "PUT",
        data: item.tmpFile, // 注意这里应上传当前切片的数据
        headers: {
          "Content-Type": file.raw.type,
        },
         signal: file.abortController.signal, // 绑定 signal
      });

      console.log("上传成功:", uploadFileRes);

      // 可选：更新进度条或状态
       // 更新已上传切片数量
      file.chunk++;
      // 更新百分比
      file.percentage = Math.round((file.uploadedChunks / file.chunks) * 100);
    }

    // 所有切片上传完成后调取合并接口
    await axios.post("/merge", {
      filename: file.md5, // 假设 uuid 应为 file.md5 或其他有效值
      size: file.size,
      chunk: fileList.length,
    });

    console.log("文件合并完成");
  } catch (error) {
    console.error("上传出错，停止后续操作:", error);
    // 这里可以添加错误提示或记录日志
  }
};

//检查文件是否上传
const checkAndUploadFile = async (file) => {
  //根据文件md5判断文件是否已经上传过
  uploadcheckFile({
    filename: file.name,
    md5: file.md5,
  }).then((res) => {
    if (res.code === 0 && res.data.exist === true) {
      file.progressStatus = "success";
      file.percentage = 100;
      file.url = res.data.url;
    } else {
      file.progressStatus = "active";
      file.percentage = 0;
      // 上传文件
      startUpload(file);
    }
  });
  console.log(createThunk(file.raw));
};
// 新增：取消上传函数
const cancelUpload = (file) => {
  if (file.abortController) {
    file.abortController.abort(); // 中断请求
  }
  file.progressStatus = "exception"; // 可以设置状态为异常或直接从列表移除
  console.log(`已取消上传文件: ${file.name}`);
};
const onChange = (file) => {
  getFileMd5(file.raw).then(async (res) => {
    file.md5 = res;
    file.chunk = 0;
    const reactiveFile = reactive(file);
    await checkAndUploadFile(reactiveFile);
    fileList.value = [...fileList.value, reactiveFile];
    console.log(fileList.value);
  });
};
const state = reactive({});
onBeforeMount(() => {});
onMounted(() => {});
defineExpose({ state });
</script>
<style lang="scss" scoped></style>
